<template>
    <div id="preview" class="container">
		<div class="mainContent">
		<div class="tableContent" >           	
			<div ref="tableContentBody" class="tableContentBody">
                <Scroll
							ref="ivScroll1"
							class="ivScroll1"
							:height="scrollHeight1"					
						>
						<table class="table" v-if="">
							<tbody class="table-body">
								<tr class="table-list"
									v-for="(row, index) in tableData.rows"								
									:key="index">
									<td class="table-item"
										v-for="(col, index) in tableData.cols"
										:class="{selected: selectedCells.includes((row - 1) * tableData.cols + col - 1)}"
										:key="index"
										:colspan="tableData.layoutDetail[(row - 1) * tableData.cols + col - 1] && tableData.layoutDetail[(row - 1) * tableData.cols + col - 1]['colSpan']"
										:rowspan="tableData.layoutDetail[(row - 1) * tableData.cols + col - 1] && tableData.layoutDetail[(row - 1) * tableData.cols + col - 1]['rowSpan']"
									    :width="tableData.layoutDetail[(row - 1) * tableData.cols + col - 1] && tableData.layoutDetail[(row - 1) * tableData.cols + col - 1]['width']"
										:height="tableData.layoutDetail[(row - 1) * tableData.cols + col - 1] && tableData.layoutDetail[(row - 1) * tableData.cols + col - 1]['height']"
										v-show="isNeedShow(row-1, col-1)"
										>
											<div class="designTdContent"
												v-html="tableData.layoutDetail[(row - 1) * tableData.cols + col - 1] && tableData.layoutDetail[(row - 1) * tableData.cols + col - 1]['content']"
									         >																	
											</div>	
		                            </td>
								</tr>
							</tbody>
						</table>
                </Scroll>							       									
			</div>
            	
		</div>
    	</div>
    </div>
</template>
<script>

    export default {
	    name:'ui-design-preview',
		components: {},
				props:{
			tableData:{
				type:Object,
				default:function(){
					return {
						
					}
				}
			}
		},
        data() {
            return {
				delIcon:null,//删除图标显示位置
				openWh1: false, //是否打开 行高 列宽
			    openWh: false, //是否打开 行高 列宽
				openSplit:false,
				tableShow:true,
			    scrollHeight1: '100%',
			    scrollMain1: false, //是否 显示
				// 这块其实初始设置 tableData： {cols: 3, rows: 2} 就可以 把tabelDate设置成计算属性，layoutDetail 用js生成更方便
				template:{
					layoutDetail:	{							
	            			colSpan: 1,
							rowSpan: 1,
							content:'',
							width:'auto',
							height:'200',
	            		},

				},
            	// tableData: {
            	// 	cols: 1,
				// 	rows: 1,
            	// layoutDetail: [ 
	            // 		{
							
	            // 			colSpan: 1,
				// 			rowSpan: 1,
				// 			content:'77',
				// 			width:'200',
				// 			height:'200',
	            // 		},
	            	
	            // 	]
            	// },
				selectedCells: [],
				// mousedown的时候设置为其他值 否则都是-1
				selectionHold: -1,
				startX: -1,
				startY: -1,
				endX: -1,
				endY: -1,
				showMenu: false,
				contextPos: {
					l: 0,
					t: 0
				}
            }
		},
	
        created() {
        },
        computed: {
		    hiddenTdMaps () {
		      	let hiddenTdMaps = {}
		      	let tableData = this.tableData
		      	for (let i = 0; i < tableData.rows; i++) {
			        for (let j = 0; j < tableData.cols; j++) {
			          	if (tableData.layoutDetail[i * tableData.cols + j]) {
			            	let colInfo = tableData.layoutDetail[i * tableData.cols + j]
			            	if ((colInfo.colSpan && colInfo.colSpan > 1) || (colInfo.rowSpan && colInfo.rowSpan > 1)) {
				              	for (let row = i; row < i + (colInfo.rowSpan || 1); row++) {
				              		// col = (row === i ? j + 1 : j) 是为了避开自己
				                	for (let col = (row === i ? j + 1 : j); col < (j + (colInfo.colSpan || 1)); col++) {
				                  		hiddenTdMaps[`${row}_${col}`] = true
				                	}
				              	}
			            	}
			          	}
		        	}
		      	}
     	 		return hiddenTdMaps
			}
		  },
		  	watch:{
			selectedCells(val){
				if(val.length<=0){
					this.delIcon=null
				}
			}
		},
        methods: {
		selectClick(index){//内容设计  选中删除
			if(this.selectedCells[0]==index){
			this.selectedCells=[]
			}else{
			this.selectedCells=[index]	
			this.delIcon=index
			}
			
		},	
		delClick(index){
			   this.tableData.layoutDetail[index].content=''
			   this.selectedCells=[]
		},
		_moveContent(e) {
                
		},
		_mouseDownContent(e,index1) {
				   let getEl = { target: e, index1: index1, index2: null,position:'relative' }
      		       this.setStore('htmlContent', getEl)
      
		},
		_mouseUpContent(index,e) {
			let tableData=JSON.parse(JSON.stringify(this.tableData))
			 let html=JSON.parse(this.getStore('htmlContent'))
			 if(html.position=='right'){
			tableData.layoutDetail[index].content=html.target	

			 }else if(html.position=='relative'){
					let contentOld=JSON.parse(JSON.stringify(this.tableData.layoutDetail[index].content))
					  tableData.layoutDetail[html.index1].content= contentOld	
					  tableData.layoutDetail[index].content=html.target
	
			 }
			 this.setStore('htmlContent', '')
			 this.tableData=tableData
		},
			changeVal(val){//获取分割界面数组
			this.openSplit = val.modal
			if (val.form) {
				this.templateRate(val.form);
				//this.pagesEl = val.form
			}
			},
			changeVal1(val) {//行高 列宽
			//获取杭高 列宽
			let tableData=JSON.parse(JSON.stringify(this.tableData))
			let num = this.selectedCells[0]//点击位置
			let ceil= Math.ceil((num+1)/this.tableData.cols);//求行
			let colNum=Math.ceil((num+1)%this.tableData.cols) //求余  获得 列数    1.。。。。n-1，n=0 n为整除
			let n = 0;//列数	
			if(colNum==0){
				n=this.tableData.cols
			}else{
				n=colNum
			}
				if (val.pattern == 'row') {
					this.openWh = val.modal
					if (val.form) {//行高
						for(let i=0;i<this.tableData.cols;i++){//列数遍历删除
										tableData.layoutDetail[ceil*this.tableData.cols-1-i].height=val.form.row
						}
					}
				} else if (val.pattern == 'col') {//列宽
					this.openWh1 = val.modal
					if (val.form) {
						   for(let i=this.tableData.rows-1;i>=0;i--){//列数遍历删除 
							            tableData.layoutDetail[n-1+i*this.tableData.cols].width=val.form.row
								}
					}
				}
				this.tableData=tableData
				this.clearSelection()
			},
				templateRate(item){
				let  layoutDetail={
						width:item.width,
						height:item.height,
						colSpan: 1,
						rowSpan: 1,
						content:'',
				}
				let data={rows:null,cols:null,layoutDetail:[]}
               data.rows=item.rows;
			   data.cols=item.cols;//  layoutDetail
			    for(let i=0;i<data.cols*data.rows;i++){
				   data.layoutDetail.push(layoutDetail)
			   }
			   this.tableData=data	
			},
			clearSelection () {
				this.selectedCells = []
			},
			changeShowMenu () {
				this.showMenu = !this.showMenu
			},
        	isNeedShow(row, col){
        		return !this.hiddenTdMaps[`${row}_${col}`]
        	},
    	  	handleCellMousedown (e, x, y) {
				this.showMenu = false
				if (e.which === 1) {
					this.endX = this.endY = -1
				}
				// e.witch = 1 是鼠标左键
				if (e.which !== 1) return
				let cellIndex = (x - 1) * this.tableData.cols + y - 1
				this.startX = x
				this.startY = y
				this.selectedCells = [cellIndex]
				// mousedown标志
				this.selectionHold = cellIndex
			},
			handleCellMouseenter (x, y) {
				if (this.selectionHold != -1) {
					this.endX = x
					this.endY = y
					this.rendSelectedCell()
				}
			},
			rendSelectedCell () {
				let startX = Math.min(this.startX, this.endX)
				let startY = Math.min(this.startY, this.endY)
				let endX = Math.max(this.startX, this.endX)
				let endY = Math.max(this.startY, this.endY)
				let tableData = this.tableData
				let selectedCells = []
				for(let row = 1; row <= tableData.rows; row++) {
					for(let col = 1; col <= tableData.cols; col++) {
						if(row >= startX && row <= endX && col >= startY && col <= endY) {
							selectedCells.push((row - 1) * this.tableData.cols + col -1)
						}
					}
				}
				this.selectedCells = selectedCells
			},
			handleMouseUp (e) {
				this.selectionHold = -1
			},
			handleContendMenu (e) {
				this.showMenu = true
				this.contextPos.l = e.pageX
				this.contextPos.t = e.pageY
			},
			reRenderTableLayout (selected,option,operation,data1) {//选择  行列  加减
				 let arr = []//空数组保存位置
				 let num = selected[0]//点击位置
				 let data= data1;//保存操作数据
				 let ceil= Math.ceil((num+1)/this.tableData.cols);//求行
				 let colNum=Math.ceil((num+1)%this.tableData.cols) //求余  获得 列数    1.。。。。n-1，n=0 n为整除
				 let n = 0;//列数			
				if(operation=='reduce'){						
							if(option=='rows'){//删除行    功能点
								for(let i=0;i<this.tableData.cols;i++){//列数遍历删除
										data.layoutDetail.splice(ceil*this.tableData.cols-1-i,1)
								}
								this.tableData=data
							
							}else if(option=='cols'){//删除列  功能点
							 if(colNum==0){
                                n=this.tableData.cols;
							 }else{
                                n=colNum;
							 }
							   for(let i=this.tableData.rows-1;i>=0;i--){//列数遍历删除 
							          data.layoutDetail.splice(n-1+i*this.tableData.cols,1)
								}
							this.tableData=data
							}
					
				} else if(operation=='plus'){
                              if(selected.length==0){//未选中的时候也可以添加
									if(option=='rows'){
									
											for(let i=0;i<this.tableData.cols;i++){//列数遍历
											data.layoutDetail.unshift(this.template.layoutDetail)	
											}								
										 this.tableData=data
									}else if(option=='cols'){   //前插入
												n=1;										
											for(let i=this.tableData.rows-1;i>=0;i--){//列数遍历    前插入
												arr.push(n-1+i*this.tableData.cols)
												data.layoutDetail.splice(n-1+i*this.tableData.cols,0,this.template.layoutDetail) 
													}	
											this.tableData=data
									}


										return
										}   
				          	if(option=='rows'){//添加行  功能点
								//行 列 点点
							
									for(let i=0;i<this.tableData.cols;i++){//列数遍历
									arr.push(this.template.layoutDetail)	
									}								
									data.layoutDetail.splice(ceil*this.tableData.cols*ceil,0,...arr)
								    this.tableData=data
							}else if(option=='cols'){//添加列  功能点
							//行 列 点点
							 if(colNum==0){
                                n=this.tableData.cols;
							 }else{
                                n=colNum;
							 }
							for(let i=this.tableData.rows-1;i>=0;i--){//列数遍历    后插入
								data.layoutDetail.splice(n-1+i*this.tableData.cols+1,0,this.template.layoutDetail) 
									}	
                             this.tableData=data
							}
				}
			},
			delOption(selected,option,operation,tips1='请选择删除项!',tips2='不支持多选删除!'){
				let data=JSON.parse(JSON.stringify(this.tableData))
				  if(selected.length==1){//修改长度  
							if(operation=='reduce'){													
							data[option] = data[option] - 1	
							} else if(operation=='plus'){
							data[option] = data[option] + 1		
							}						
							this.reRenderTableLayout(selected,option,operation,data);
							this.clearSelection();
					  }else if(selected.length==0){//等于零时候   为 行 列 加
								if((operation=='plus'&&option=='rows')|(operation=='plus'&&option=='cols')){
										if(operation=='reduce'){						
										data[option] = data[option] - 1	
										} else if(operation=='plus'){
										data[option] = data[option] + 1		
										}	
								this.reRenderTableLayout(selected,option,operation,data);
							}else{
							this.$Message.warning(tips1)	
							}
					  }else if(selected.length<1){
                           	this.$Message.warning(tips1)
					  }	else if(selected.length>1){
                           	this.$Message.warning(tips2)
					  }	
			},
			menyItemCmd (cmd,selected) {
				let tableData =JSON.parse(JSON.stringify(this.tableData))
				let startX = Math.min(this.startX, this.endX)
				let startY = Math.min(this.startY, this.endY)
				let endX = Math.max(this.startX, this.endX)
				let endY = Math.max(this.startY, this.endY)
				switch (cmd) {
					case 'merge':										
					if((startX === -1 || startY === -1 || endX === -1 || endY === -1) || ((startX === endX) && (startY === endY))) return
					let startIndex = (startX - 1) * tableData.cols +  startY - 1
					tableData.layoutDetail[startIndex].rowSpan = endX - startX + 1
					tableData.layoutDetail[startIndex].colSpan = endY - startY + 1
					this.tableData=tableData
					this.clearSelection()
					break
					case 'split':                               
						this.selectedCells.forEach(v => {//拆分
						this.tableData.layoutDetail[v].rowSpan = 1
						this.tableData.layoutDetail[v].colSpan = 1
					})
					this.clearSelection()
					break
					case 'delRow':
					this.delOption(selected,'rows','reduce')				
					break
					case 'pageSplit':
					this.openSplit=true;	
					this.clearSelection()		
					break
					case 'delCol':
					this.delOption(selected,'cols','reduce')				
					break
					case 'addRow':
					this.delOption(selected,'rows','plus','请选择添加项!','不支持多选!')
					break
					case 'addCol':
					this.delOption(selected,'cols','plus','请选择添加项!','不支持多选!')
					break
					case 'rowHeight':
                    this.designWh('openWh')
					break
					case 'colWidth':
					this.designWh('openWh1')
					break
					case 'designLayout':
						this.tableShow=true
						this.clearSelection()
					break	
					case 'designContent':
						this.tableShow=false
						this.clearSelection()
					break	
					case 'clearSelection':
					this.clearSelection()
					break
					
				}			
				this.changeShowMenu()
			},
			designWh(item){
				if(this.selectedCells.length==1){
                  this[item]=true
				}else{
                this.$Message.warning('不支持多选!')
				}
				
			}
		},
		mounted(){
			this.scrollHeight1 = this.$refs.tableContentBody.offsetHeight
		}
    }
</script>

<style lang='less'>
.container{
	-webkit-touch-callout: none; /* iOS Safari */
	-webkit-user-select: none; /* Chrome/Safari/Opera */
	-khtml-user-select: none; /* Konqueror */
	-moz-user-select: none; /* Firefox */
	-ms-user-select: none; /* Internet Explorer/Edge */
	user-select: none; /* Non-prefixed version, currently*/
	position: relative;
	width: 100%;
	height: 100%;}
#preview{
.switchTitle {
	height: 50px;
}
  .switchClose{
      float: right;
      cursor: pointer;
      position: relative;
      top: 10px;
    
    }
.switchButton {
	margin-right: 16px;
}
.mainContent {
	border: 1px solid rgba(220, 222, 226, 1);
	width: 100%;
	height: calc(~'100%');
}
 
    .tableContent{
		width: 100%;
        height:100%;
        padding-top: 0px;
	}
	.tableContentBody{
			 width: 100%;
		height:100%;
	}
	.table{
		border-collapse:collapse;
		width: 100%;
	    height: 100%;

		.table-body{
			.table-list{
				height: 50px;
				line-height: 50px;
				td{
                    padding:0;
                    border: none;
				}
			}
		}
	}
.designTdContent{
	width: 100%;
	height: 100%;
}
.tableCursor{
	cursor: pointer;
	position: relative;
	.delIcon{
		display: none;
		width: 16px;
		height: 16px;
		position: absolute;
		right: 10px;
		top: 10px;
		background: url('../../../../assets/design/icon/del (1).png') no-repeat;
		background-size: 100% 100%;
		background-position: center center;
		z-index: 10;
	}
	.delIcon1{
		display: inline-block;
	}
}
&/deep/ .ivu-scroll-loader{
    display: none;
}
&/deep/ .ivu-scroll-content{
	width: 100%;
	height: 100%;    
}
}
</style>